import traceback
import requests
from PyQt5 import QtCore, QtWidgets, QtGui
from requests import models


class SubmitToTrading(QtWidgets.QDialog):
    def __init__(
        self, stragtegy_file_path: str, class_name: str, parameters: dict, variables: list
    ):
        """"""
        super(SubmitToTrading, self).__init__()
        self.class_name = class_name
        self.stragtegy_file_path = stragtegy_file_path
        self.parameters = parameters
        self.variables = variables

        self.setupUi(self)

    def setupUi(self, Dialog):
        Dialog.resize(446, 560)
        self.widget = QtWidgets.QWidget(Dialog)
        self.widget.setGeometry(QtCore.QRect(10, 10, 426, 544))

        self.verticalLayout = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout = QtWidgets.QGridLayout()
        self.strategy_label = QtWidgets.QLabel(self.widget)
        self.gridLayout.addWidget(self.strategy_label, 0, 0, 1, 1)
        self.strategy_formLayout = QtWidgets.QFormLayout()
        self.code_label = QtWidgets.QLabel(self.widget)
        self.strategy_formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.code_label)
        self.strategy_name = QtWidgets.QLabel(self.widget)
        self.strategy_formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.strategy_name)
        self.strategy_params = QtWidgets.QLabel(self.widget)
        self.strategy_formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.strategy_params)
        self.tableView_parameters = QtWidgets.QTableView(self.widget)
        self.strategy_formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.tableView_parameters)
        self.tableView_variables = QtWidgets.QTableView(self.widget)
        self.strategy_formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.tableView_variables)
        self.label = QtWidgets.QLabel(self.widget)
        self.strategy_formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label)
        self.gridLayout.addLayout(self.strategy_formLayout, 0, 1, 1, 1)

        self.param_model = QtGui.QStandardItemModel(len(self.parameters), 2)
        self.param_model.setHorizontalHeaderLabels(['参数名','参数值'])
        row_num = 0
        for param_name, param_val in self.parameters.items():
            for col_num in range(2):
                content = QtGui.QStandardItem(str(param_name) if col_num==0 else str(param_val))
                content.setEditable(False)
                self.param_model.setItem(row_num, col_num, content)
            row_num += 1
        self.tableView_parameters.setModel(self.param_model)

        self.var_model = QtGui.QStandardItemModel(len(self.parameters), 1)
        self.var_model.setHorizontalHeaderLabels(['变量名'])
        for index, var in enumerate(self.variables):
            self.var_model.setItem(index, 0, QtGui.QStandardItem(var))
        self.tableView_variables.setModel(self.var_model)

        self.trading_env_label = QtWidgets.QLabel(self.widget)
        self.gridLayout.addWidget(self.trading_env_label, 1, 0, 1, 1)
        
        # 仿真环境信息框
        self.tradingLayout = QtWidgets.QFormLayout()

        self.url = QtWidgets.QLineEdit("http://httpbin.org/post")
        self.username = QtWidgets.QLineEdit("admin")
        self.password = QtWidgets.QLineEdit("admin")

        self.url_label = QtWidgets.QLabel(self.widget)
        self.tradingLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.url_label)
        self.tradingLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.url)
        self.username_label = QtWidgets.QLabel(self.widget)
        self.tradingLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.username_label)
        self.tradingLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.username)
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.password_label = QtWidgets.QLabel(self.widget)
        self.tradingLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.password_label)
        self.tradingLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.password)

        self.gridLayout.addLayout(self.tradingLayout, 1, 1, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        self.buttonBox = QtWidgets.QDialogButtonBox(self.widget)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.addButton(QtWidgets.QDialogButtonBox.Cancel)
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setText("取消")
        self.buttonBox.addButton(QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setText("确认")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(self.submit)
        self.buttonBox.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "仿真发布"))
        self.strategy_label.setText(_translate("Dialog", "策略信息"))
        self.code_label.setText(_translate("Dialog", "策略名称："))
        self.strategy_name.setText(_translate("Dialog", self.class_name))
        self.strategy_params.setText(_translate("Dialog", "策略参数："))
        self.label.setText(_translate("Dialog", "策略变量："))

        self.trading_env_label.setText(_translate("Dialog", "仿真环境"))
        self.url_label.setText(_translate("Dialog", "url地址："))
        self.username_label.setText(_translate("Dialog", "用户名："))
        self.password_label.setText(_translate("Dialog", "密码："))

    
    def submit(self):
        streategy_code = open(self.stragtegy_file_path, encoding='utf-8').read()

        payload = {
            'stgname': self.class_name,
            'stgfile':streategy_code,
            'stgpara': [{'paraname': k, 'paravalue': v} for k,v in self.parameters.items()],
            'stgvar': [{'varname': var} for var in self.variables]
        }
        submit_status = ''
        try:
            res = requests.post(self.url.text(), data=payload, timeout=10)
            if res.status_code == 200:
                submit_status = '发布成功'
                # 发布成功后关闭发布框
                self.accept()
            else:
                submit_status = f'发布失败!\n{res.text}'
        except Exception as e:
            submit_status = f'发布失败!\n{traceback.format_exc()}'
        finally:
            QtWidgets.QMessageBox.information(self, '发布结果', '仿真环境暂未开放。', QtWidgets.QMessageBox.Yes)

